<template>
  <div class="wrap">
      <div class="img" ref="coding"></div>
  </div>
</template>

<script>
export default {
  name: "magnifier",
  mounted() {
    let img = this.$refs['coding']
    // PC
    img.addEventListener('mouseenter',this.enterHandler)
    img.addEventListener('mousemove',this.moveHandler)
    img.addEventListener('mouseleave',this.leaveHandler)
    // 移动端
    img.addEventListener('touchstart',this.enterHandler)
    img.addEventListener('touchmove',this.moveHandler)
    img.addEventListener('touchend',this.leaveHandler)
  },
  methods:{
    enterHandler(e){
      e.target.setAttribute('zoomed',1)
      // this.moveHandler(e)
    },
    moveHandler(e){
      // pc
      let rect = e.target.getBoundingClientRect(),
       offsetX, offsetY // 兼容移动端
       console.log(e.type)
      if(['touchstart','touchmove','touchend'].includes(e.type)){
        offsetX = e.touches[0].pageX - rect.left  // 第一个触碰点
        offsetY = e.touches[0].pageY - rect.top  // 第一个触碰点
        e.preventDefault() // 阻止默认行为
      }else {
        offsetX = e.offsetX
        offsetY = e.offsetY
      }
      let x = offsetX / rect.width, 
          y = offsetY / rect.height;
      e.target.style.setProperty('--x', x)
      e.target.style.setProperty('--y', y)
      
    },
    leaveHandler(e){
      e.target.removeAttribute('zoomed')
      // this.moveHandler(e)
    },
  }
}; 
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
